package com.gzdcdata.home.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.gzdcdata.core.common.ApiController;
import com.gzdcdata.core.common.PublicInterfaceWX;
import com.gzdcdata.core.common.ResponseData;
import com.gzdcdata.core.common.StringUtil;
import com.gzdcdata.wxpay.service.WXPayCommenService;
import com.gzdcdata.xxad.entity.XxAd;
import com.gzdcdata.xxad.service.XxAdService;
import com.gzdcdata.xxmember.entity.XxMember;
import com.gzdcdata.xxmember.service.XxMemberService;
import com.gzdcdata.xxorder.service.XxOrderService;
import com.gzdcdata.xxproduct.entity.XxProduct;
import com.gzdcdata.xxproduct.service.XxProductService;
import com.gzdcdata.xxproductcategory.entity.XxProductCategory;
import com.gzdcdata.xxproductcategory.service.XxProductCategoryService;
import com.gzdcdata.xxtag.entity.XxTag;
import com.gzdcdata.xxtag.service.XxTagService;

/**
 * 微信商城首页
 * @author dsj
 *
 */
@Controller
@RequestMapping("/home")
public class HomeController extends ApiController{

	/*@Value("${GET_CODE_URL}")
	private String GET_CODE_URL;*/
	@Resource(name="xxMemberService")
	private XxMemberService  xxMemberService;

	@Resource(name="xxAdService")
	private XxAdService xxAdService;
	@Resource(name="xxProductCategoryService")
	private XxProductCategoryService xxProductCategoryService;
	@Resource(name="xxTagService")
	private XxTagService xxTagService;
	@Resource(name="xxProductService")
	private XxProductService xxProductService;
	@Resource(name="xxOrderService")
	private XxOrderService xxOrderService;

	@Resource(name="wXPayCommenService")
	private WXPayCommenService wXPayCommenService;
	@GetMapping("")
	public ResponseEntity<ResponseData> indexPageData(){
		logger.info("首页信息获取！");
		Map<String,Object> resultMap=new HashMap<String,Object>() ;

		List<XxAd> xxads=xxAdService.getAllAd();
		resultMap.put("xxads", xxads);

		List<XxProductCategory> xxProductCategory=xxProductCategoryService.getAllProductCategoryData();
		resultMap.put("xxProductCategory", xxProductCategory);

		List<XxTag> xxTagsList=xxTagService.getAllTagsProduct();
		resultMap.put("xxTagsList", xxTagsList);

		PageInfo<XxProduct> xxProductListPage=xxProductService.getXxProductByPage(1,10);
		resultMap.put("xxProductListPage", xxProductListPage);
		return new ResponseEntity<ResponseData>(success(resultMap),HttpStatus.OK);
	}

	  /**
     *登录
     * @param request
     * @param response
     * @return
     */
	@RequestMapping(value="/login")
	public ResponseEntity<ResponseData> login(HttpServletRequest request) {
		String code =  request.getParameter("code");
		logger.info("用户登录。。"+code);
		if(code == null || "".equals(code)){
			return  new ResponseEntity<ResponseData>(fail("没有授权，请重试！"),HttpStatus.BAD_GATEWAY);
		}
		//通过code获取了用户信息
	    JSONObject json = PublicInterfaceWX.getWXInfo(code);
	    if(json == null|| json.getString("openid")==null){
			return  new ResponseEntity<ResponseData>(fail("code参数不正确！"),HttpStatus.BAD_GATEWAY);
		}
	    String openid =json.getString("openid");
	    XxMember xxMember=xxMemberService.getXxMemberInfoByOpenid(openid);
	    if(xxMember!=null&&xxMember.getId()!=null){//登录
	    	return new ResponseEntity<ResponseData>(success(xxMember),HttpStatus.OK);
	    }else{//注册登录
	    	String nickname=json.getString("nickname");
	    	Integer sex=json.getInteger("sex");
	    	//String language=UserInfoJson.getString("language");
	    	String city=json.getString("city");
	    	String province=json.getString("province");
	    	String country=json.getString("country");
	    	String headimgurl=json.getString("headimgurl");
	    	XxMember xxMemberTemp=new XxMember();
	    	xxMemberTemp.setAttribute_value1(openid);
	    	xxMemberTemp.setAddress(country+province+city);
	    	xxMemberTemp.setNick_name(nickname);
	    	xxMemberTemp.setGender(sex);
	    	xxMemberTemp.setAttribute_value0(headimgurl);
	    	xxMemberTemp.setLogin_ip(getRemortIP(request));
	    	logger.info("注册信息"+xxMemberTemp.toString());
	    	xxMemberTemp=xxMemberService.addUserInfo(xxMemberTemp);
	    	logger.info("注册并返回登录信息包含id"+xxMemberTemp.toString());
	    	return new ResponseEntity<ResponseData>(success(xxMemberTemp),HttpStatus.OK);
	    }
	}
	public String getRemortIP(HttpServletRequest request) {
		  if (request.getHeader("x-forwarded-for") == null) {
		   return request.getRemoteAddr();
		  }
		  return request.getHeader("x-forwarded-for");
		}
	/**
	 * 个人主页加载一些统计信息
	 * @param memberId
	 * @return
	 */
	@GetMapping("/leadStatusData")
	public ResponseEntity<ResponseData> leadStatusData(String memberId,
			@RequestParam(defaultValue="0",name="order_status")String order_status){
		logger.info("个人主页统计信息获取"+memberId+"订单状态"+order_status);
		Map<String,Object> result=new HashMap<String,Object>();
		if(StringUtil.isNumeric(memberId)&&StringUtil.isNumeric(order_status)){//判断为数字且不为空
			result.put("orderTotal", xxOrderService.countByStatusMember(memberId,order_status));
			return new ResponseEntity<ResponseData>(success(result),HttpStatus.OK);
		}
		return  new ResponseEntity<ResponseData>(fail("参数不正确！"),HttpStatus.BAD_GATEWAY);
	}
	/**
	 * 特殊情况:本商城登录授权的微信公众号是运行的公众号
	 * 在此支付的收款是另一个公众号服务,所有这个方法特别用来获取用户和收款公众号绑定的appid
	 * @return
	 */
	@RequestMapping("/getAppidByCode")
	public ResponseEntity<ResponseData> getAppidByCode(HttpServletRequest request){
		String code =  request.getParameter("code");
		if(code == null || "".equals(code)){
			return  new ResponseEntity<ResponseData>(fail("授权错误，请重试！"),HttpStatus.BAD_GATEWAY);
		}
	    JSONObject json = wXPayCommenService.getWXInfo(code);
	    if(json == null|| json.getString("openid")==null){
			return  new ResponseEntity<ResponseData>(fail("code参数不正确！"),HttpStatus.BAD_GATEWAY);
		}
	    logger.info("通过code获取的openid等信息"+json);
	    //String openid =json.getString("openid");
		return new ResponseEntity<ResponseData>(success(json),HttpStatus.OK);
	}
}


